package org.coderjonny.service.impl;

import org.coderjonny.bean.Order;
import org.coderjonny.bean.OrderItem;
import org.coderjonny.bean.Product;
import org.coderjonny.bean.User;
import org.coderjonny.constant.HttpCode;
import org.coderjonny.dto.order.OrderParam;
import org.coderjonny.dto.Result;
import org.coderjonny.dto.order.OrderResult;
import org.coderjonny.exception.BusinessException;
import org.coderjonny.mapper.OrderItemMapper;
import org.coderjonny.mapper.OrderMapper;
import org.coderjonny.repository.OrderRepository;
import org.coderjonny.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private OrderRepository repository;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult createOrder(OrderParam orderParam) {
        User user = repository.queryUserById(orderParam);
        if (user == null){
            throw new BusinessException("用户不存在");
        }
        Product product = repository.queryProductById(orderParam);
        if (product == null){
            throw new BusinessException("商品不存在");
        }
        if (product.getProStock() < orderParam.getCount()){
            throw new BusinessException("库存不足");
        }
        Order order = new Order();
        order.setUserId(orderParam.getUserId());
        order.setPhone(user.getPhone());
        order.setAddress(user.getAddress());
        order.setUsername(user.getUsername());
        order.setTotalPrice(product.getProPrice().multiply(BigDecimal.valueOf(orderParam.getCount())));
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setNumber(orderParam.getCount());
        orderItem.setProId(orderParam.getProductId());
        orderItem.setProName(product.getProName());
        orderItem.setProPrice(product.getProPrice());
        Integer updatedStockResult = repository.updateStock(orderParam);
        if (updatedStockResult == HttpCode.FAILURE){
            throw new BusinessException("扣减库存失败");
        }
        orderMapper.insert(order);
        orderItemMapper.insert(orderItem);
        OrderResult orderResult = new OrderResult();
        orderResult.setOrderId(order.getId());
        return orderResult;
    }
}
